var util = require('../../libs/util.js');
var app = getApp()
Page({
  data: {
    hasData: false,
    userInfo: {},
    truename: "",
    dialog: false,
    searchShowed: false,
    searchVal: "",
  },
  // onShareAppMessage: function () {
  //   return {
  //     title: app.appName,
  //     path: '/pages/index/index'
  //   }
  // },
  onLoad: function (e) {
    var that = this;
    that.setData({
      isAdmin: app.globalData.admin == '1' ? true : false,
      isCoAdmin: app.globalData.coAdmin == '1' ? true : false,
      isFleet: app.globalData.role_default == 'fleet' ? true : false,
      vehicleTag: util.vehicleTag
    })
    this.loadData();
  },
  onShow: function () {
  },
  showSearch: function () {
    this.setData({
      searchShowed: true
    });   
  },
  hideSearch: function () {
    this.setData({
      searchVal: "",
      searchShowed: false
    });
    this.loadData();
  },
  clearSearch: function () {
    this.setData({
      searchVal: ""
    });
    this.loadData();
  },
  searchTyping: function (e) {
    this.setData({
      searchVal: e.detail.value
    });
    this.loadData();
  },
  loadData: function () {
    wx.showLoading({
      title: '加载数据中...',
    });
    var that = this;
    this.setData({
      is_admin: app.globalData.admin == '1' ? true : false
    })
    util.getData2("vehicleManage", {
      CO_ID: app.globalData.CO_ID,
      sql: that.data.searchVal
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (res.data.success) {
        that.setData({
          hasData: true
        });
        var data = res.data.data,_data = [];
        for (var i = 0; i < data.length;i++){
          _data.push({
            ID: data[i].ID,
            plate: data[i].plate,
            name: data[i].name || "未绑定",
            bindDriver: (data[i].name ? true : false),
            name2: data[i].name2 || "未绑定",
            bindDriver2: (data[i].name2 ? true : false),
            ischeck: (data[i].ischeck == '1'?true:false),
            warehouse: data[i].abbreviation || data[i].wh_name || "暂无项目",
            plate_owner: data[i].plate_owner || "无",
            carrier: data[i].carrier||"无",
            loadage: data[i].loadage||0,
            CO_NAME: data[i].CO_NAME || "无",
            capacity_company: data[i].capacity_company,
            vehicleFunction:data[i].vehicleFunction,
            semitrailer_plate:data[i].semitrailer_plate||'',
            semitrailer:data[i].semitrailer||'',
            tags: data[i].tags ? String(data[i].tags).split(","):[]
          });
        }
        that.setData({
          vehicleData: _data
        })
      }else{
        that.setData({
          vehicleData: []
        })
      }
    });
  },
  deleteVehicle: function (e) {
    var id = e.currentTarget.id;
    wx.showModal({
      title: '删除车辆',
      content: '是否确认删除车辆',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '请稍候...',
          });
          util.putData("deleteVehicle", {
            id: id,
            openid: app.globalData.openid
          }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
            if (res.data.success) {
              wx.showLoading({
                title: "删除成功",
                icon: 'success',
                success: function () {
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages/fleet/vehicle'
                    })
                  }, 3000);
                }
              });
            } else {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
          });
        } else if (res.cancel) {
        }
      }
    })
  },
  dispatchCompany: function (e) {
    var that = this;
    that.setData({
      currentVehicleId: e.currentTarget.id
    })
    util.getData('/wechat/passport/getCompany', {}, function (res) {
      console.log(res.data.data)
      if (res.data.success) {
        that.setData({
          enterpriseList: res.data.data
        })
      }
    });
    that.setData({
      modalName: 'enterpriseModal'
    })

  },
  cancelDispatchCompany: function (e) {
    var that = this;
    var vehicleId = that.data.currentVehicleId;
    wx.showModal({
      title: '温馨提示',
      content: '确认要取消派遣吗？取消后，目前所在的承运商将无法给你派单',
      success(res) {
        if (res.confirm) {
          util.putData("/wechat/vehicle/cancelDispatchVehicleToCompany", {
            id: that.data.vehicle_id
          }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
            if (res.data.success) {
              wx.showModal({
                title: '温馨提示',
                content: '取消派遣成功！',
                success: function (res) {
                  wx.redirectTo({
                    url: '/pages/index/index'
                  })
                }
              })
            } else if (res.data.success == false) {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000,
                mask: true
              });
            }
          });
        }
      }
    })

  },
  enterpriseInput: function (e) {
    var that = this;
    var value = e.detail.value;
    var enterpriseList = that.data.enterpriseList;
    var _enterpriseList = [];
    for (var i = 0; i < enterpriseList.length; i++) {
      if (enterpriseList[i].CO_NAME.indexOf(value) > -1) {
        _enterpriseList.push(enterpriseList[i]);
      }
    };
    if (value == '') {
      _enterpriseList = [];
    }
    that.setData({
      _enterpriseList: _enterpriseList
    })
  },
  selectEnterprise: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var _enterpriseList = that.data._enterpriseList;
    for (var i = 0; i < _enterpriseList.length; i++) {
      if (_enterpriseList[i].CO_ID == id) {
        that.setData({
          CO_NAME: _enterpriseList[i].CO_NAME,
          CO_ID: _enterpriseList[i].CO_ID
        })
        util.putData("/wechat/vehicle/dispatchVehicleToCompany", {
          id: that.data.currentVehicleId,
          company: _enterpriseList[i].CO_ID
        }, function (res, error) {
          console.log(res); console.log(error)
          wx.hideLoading();
          if (error) {
            wx.showToast({
              title: res.data.data,
              image: '/images/wrong.png',
              duration: 3000
            });
            return false;
          }
          if (res.data.success) {
            wx.showModal({
              title: '温馨提示',
              content: '派遣成功！',
              success: function (res) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            })
          } else if (res.data.success == false) {
            wx.showToast({
              title: res.data.data,
              image: '/images/wrong.png',
              duration: 3000,
              mask: true
            });
          }
        });
        that.hideModal();
        return false;
      }
    };
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target
    })

    if (e.currentTarget.dataset.target == 'tagModal'){
       that.setData({
         currentId: e.currentTarget.dataset.id
       })
    }
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  deleteDriver: function (e) {
    var id = e.currentTarget.id;
    var sub = e.currentTarget.dataset.sub;
    console.log(sub)
    wx.showModal({
      title: '解除绑定司机',
      content: '是否确认解除本车辆所绑定的'+(sub=='false'?'主':'副')+'司机？',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '请稍候...',
          });
          util.putData("vehicleUnBindDriver", {
            id: id,
            sub:sub,
            openid: app.globalData.openid,
            user_id: app.globalData.user_id,
            CO_ID: app.globalData.CO_ID
          }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
            if (res.data.success) {
              wx.showToast({
                title: "解除绑定成功",
                icon: 'success',
                success: function () {
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages/fleet/vehicle'
                    })
                  }, 3000);
                }
              });
            } else {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
          });
        } else if (res.cancel) {
        }
      }
    })
  },
  bindDriver: function (e) {
    var id = e.currentTarget.id;
    wx.redirectTo({
      url: '/pages/fleet/vehicleBindDriver?CO_ID=' + app.globalData.CO_ID+'&id='+id+'&url=/pages/fleet/vehicle'
    })
  }, 
  bindDriver2: function (e) {
    var id = e.currentTarget.id;
    wx.redirectTo({
      url: '/pages/fleet/vehicleBindDriver?sub=true&CO_ID=' + app.globalData.CO_ID+'&id='+id+'&url=/pages/fleet/vehicle'
    })
  }, 
  dispatch: function(e) {
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/fleet/vehicleBindWarehouse?id=' + id
    })
  },
  bindSemitrailer: function (e) {
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/vehicle/semitrailer_select?CO_ID=' + app.globalData.CO_ID+'&id='+id
    })
  }, 
  verifyVehicle:function(e){
    var id = e.currentTarget.id;
    var vehicleData = this.data.vehicleData,ischeck = false,plate = '';
    for (var i = 0; i < vehicleData.length;i++){
      if (vehicleData[i].ID == id && vehicleData[i].ischeck == true){
        ischeck = true;
        plate = vehicleData[i].plate;
        break;
      }
    };
    if(ischeck){
      wx.showModal({
        title: '车辆审核',
        content: '车辆（'+plate+'）已审核通过',
        showCancel: false,
        success: function (res) {
        }
      })
      return false;
    }else{
      wx.showModal({
        title: '车辆审核',
        content: '是否确认审核通过',
        success: function (res) {
          if (res.confirm) {
            wx.showLoading({
              title: '请稍候...',
            });
            util.putData("/atapi/vehicle/vehicle/verifyVehicle", {
              id: id,
              CO_ID: app.globalData.CO_ID
            }, function (res, error) {
              console.log(res); console.log(error)
              wx.hideLoading();
              if (error) {
                wx.showToast({
                  title: '审核失败',
                  image: '/images/wrong.png',
                  duration: 3000
                });
                return false;
              }
              if (res.data.success) {
                wx.showLoading({
                  title: "审核通过",
                  icon: 'success',
                  success: function () {
                    setTimeout(function () {
                      wx.redirectTo({
                        url: '/pages/fleet/vehicle'
                      })
                    }, 3000);
                  }
                });
              } else {
                wx.showToast({
                  title: '审核失败',
                  image: '/images/wrong.png',
                  duration: 3000
                });
                return false;
              }
            });
          } else if (res.cancel) {
          }
        }
      })
    }
  },
  setLoadage:function(e){
    var loadage = e.currentTarget.dataset.loadage;
    var setLoadageVehiceId = e.currentTarget.id;
    this.setData({
      loadageInput:loadage||0,
      dialog:true,
      setLoadageVehiceId: setLoadageVehiceId
    })
  },
  addTag:function(e){
    var that = this;
     var tag = e.currentTarget.dataset.tag;
    var id = that.data.currentId;
    var vehicleData = that.data.vehicleData;
    var newtag = '';
    for (var i = 0; i < vehicleData.length;i++){
      if (vehicleData[i].ID == id){
        var tagArray = vehicleData[i].tags;
        if (!tagArray){
          tagArray = [];
          tagArray.push(tag);
          newtag = tagArray.join(",");
        }else{
          if (tagArray.indexOf(tag) > -1){
            wx.showToast({
              title: '同名分类已存在',
              image: '/images/wrong.png',
              duration: 3000
            });
            return false;
          } else {
            tagArray.push(tag);
            newtag = tagArray.join(",");
          }
        }
      }
    }
    that.setData({
      vehicleData: vehicleData,
      modalName:null
    });
    if (newtag){
      that.saveNewTag(id, newtag);
    }
  },
  addNewTag: function (e) {
    var that = this;
    var tag = that.data.newtag;
    if (!tag) {
      wx.showToast({
        title: '请输入标签名称',
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    var id = that.data.currentId;
    var vehicleData = that.data.vehicleData;
    var newtag = '';
    for (var i = 0; i < vehicleData.length; i++) {
      if (vehicleData[i].ID == id) {
        var tagArray = vehicleData[i].tags;
        if (!tagArray) {
          tagArray = [];
          tagArray.push(tag);
          newtag = tagArray.join(",");
        } else {
          if (tagArray.indexOf(tag) > -1) {
            wx.showToast({
              title: '同名分类已存在',
              image: '/images/wrong.png',
              duration: 3000
            });
            return false;
          } else {
            tagArray.push(tag);
            newtag = tagArray.join(",");
          }
        }
        vehicleData[i].tags = tagArray;
        break;
      }
    }
    that.setData({
      vehicleData: vehicleData,
      modalName: null
    })
    if (newtag) {
      that.saveNewTag(id, newtag);
    }
  },
  saveNewTag:function(id,tags){
    util.postData("/atapi/vehicle/vehicle/saveVehicleTag", {
      id: id,
      tags: tags
    }, function (res, error) {
      if (res.data.success) {
        wx.showToast({
          title: '设置成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            
          }
        })

      } else {
        wx.showToast({
          title: '设置失败',
          icon: 'success',
          duration: 2000
        })
      }
    });
  },
  deleteTag:function(e){
    var that = this;
    var tag = e.currentTarget.dataset.tag;
    var id = e.currentTarget.dataset.id;
    var vehicleData = that.data.vehicleData;
    var newtag = '';
    for (var i = 0; i < vehicleData.length; i++) {
      if (vehicleData[i].ID == id) {
        var tags = vehicleData[i].tags;
        newtag = vehicleData[i].tags = util.arrayDeleteItem(vehicleData[i].tags, tag);
      }
    }
    if(newtag){
      wx.showModal({
        title: '温馨提示',
        content: '确认要删除分类【' + tag+'】吗？',
        success(res) {
          if (res.confirm) {
            that.setData({
              vehicleData: vehicleData
            });
            that.saveNewTag(id, newtag);
          }
        }
      })
    }
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  confirmDialogSetBtn:function(){
    var setLoadageVehiceId = this.data.setLoadageVehiceId;
    var loadage = this.data.loadageInput;
    wx.showLoading({
      title: '设置中...',
    });
    var selectedData = this.data.selectedData; console.log(selectedData)
    var vehicleId = this.data.vehicleId;
    util.putData("setVehicleLoadage", {
      loadage: loadage,
      vehicleId: setLoadageVehiceId
    }, function (res, error) {
      if (res.data.success) {
        wx.showToast({
          title: '设置成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            wx.redirectTo({
              url: '/pages/fleet/vehicle'
            })
          }
        })

      } else {
        wx.showToast({
          title: '设置失败',
          icon: 'success',
          duration: 2000
        })
      }
      wx.hideLoading();
    });
  },
  cancelDialogSetBtn:function(){
    this.setData({
      dialog:false
    })
  },
  onShow: function (e) {
    var that = this;
    wx.getStorage({
      key: 'semitrailer_select',
      success: function (res) {
        if (res.data) {
          wx.showLoading({
            title: '绑定中...',
          });
          var vehicleData = that.data.vehicleData,plate = '';
          for (var i = 0; i < vehicleData.length;i++){
            if (vehicleData[i].ID == res.data.vehicleId){
              plate = vehicleData[i].plate;
              break;
            }
          };
          util.putData("/atapi/vehicle/vehicle/vehicleBindSemitrailer", {
            vehicleId: res.data.vehicleId,
            semitrailer: res.data.ID,
            semitrailer_plate:res.data.plate,
            plate:plate,
            openid: app.globalData.openid,
            user_id: app.globalData.user_id,
            CO_ID: app.globalData.CO_ID
          }, function (res, error) {
            if (res.data.success) {
              wx.showToast({
                title: '绑定成功',
                icon: 'success',
                duration: 2000,
                success: function () {
                  setTimeout(function () {
                    that.loadData();
                  }, 3000);
                }
              })
      
            } else {
              wx.showToast({
                title: '绑定失败',
                icon: 'success',
                duration: 2000
              })
            }
            wx.hideLoading();
          });
        }
      },
      complete: function (res) {
        wx.removeStorage({
          key: 'semitrailer_select',
          success: function (res) {
          }
        });
      }
    });
  },
  deleteSemitrailer: function (e) {
    var that = this;
    var id = e.currentTarget.id;
    wx.showModal({
      title: '解除挂车绑定',
      content: '是否确认解除本车辆所绑定的挂车？',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '请稍候...',
          });
          var vehicleData = that.data.vehicleData,currentItem = '';
          for (var i = 0; i < vehicleData.length;i++){
            if (vehicleData[i].ID == id){
              currentItem = vehicleData[i];
              break;
            }
          };
          util.putData("/atapi/vehicle/vehicle/vehicleUnBindSemitrailer", {
            vehicleId: currentItem.ID,
            semitrailer: currentItem.semitrailer,
            semitrailer_plate:currentItem.semitrailer_plate,
            plate:currentItem.plate,
            openid: app.globalData.openid,
            user_id: app.globalData.user_id,
            CO_ID: app.globalData.CO_ID
          }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
            if (res.data.success) {
              wx.showToast({
                title: "解除绑定成功",
                icon: 'success',
                success: function () {
                  setTimeout(function () {
                    that.loadData();
                  }, 3000);
                }
              });
            } else {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
          });
        } else if (res.cancel) {
        }
      }
    })
  },
  gotoHome: function () {
    wx.navigateTo({
      url: '/pages/fleet/fleet'
    })
  },
  gotoVehicle: function () {
    wx.navigateTo({
      url: '/pages/fleet/vehicle'
    })
  },
  gotoSemitrailer: function () {
    wx.navigateTo({
      url: '/pages/vehicle/semitrailer'
    })
  },
  gotoDriver: function () {
    wx.navigateTo({
      url: '/pages/enterprise/user_driver?type=fleet'
    })
  },
  gotoInfo: function () {
    wx.navigateTo({
      url: '/pages/fleet/apps'
    })
  },
  gotoTransportCapacity:function(){
    wx.navigateTo({
      url: '/pages/vehicle/transport_capacity'
    })
  }
})
